package xyz.mimai.media.netty.http;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

/**
 * @ClassName HttpServerChannelInitializer
 * @Description TODO
 * @Author 方丈
 * @Date 2021/2/5 9:31
 * @Version 1.0.0
 **/
public class HttpServerChannelInitializer extends ChannelInitializer<SocketChannel> {
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        //添加一个netty自带的http的编码解码器
        socketChannel.pipeline().addLast(new HttpServerCodec());
       // socketChannel.pipeline().addLast("httpAggregator",new HttpObjectAggregator(512*1024)); // http 消息聚合器
        //添加一个自定义的业务处理handler
        socketChannel.pipeline().addLast("selfHttpHandler",new SelfDefineHttpServerHandler());
    }

    /**
     * 自定义业务处理
     */
    public static class SelfDefineHttpServerHandler extends SimpleChannelInboundHandler<HttpObject> {

        @Override
        protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpObject o) throws Exception {

            if(o instanceof HttpContent){
                System.out.println("不作处理的消息类型....");
                return;
            }

            System.out.println("接收到请求，开始处理....");

            if(o instanceof HttpRequest){
                HttpRequest request = (HttpRequest) o;
                String uri = request.uri();
                System.out.println("访问地址是:"+uri+",访问的http method："+request.method());
            }

            System.out.println("接收到请求，处理结束....");
            String resp="服务器收到请求，你的地址是:"+channelHandlerContext.channel().remoteAddress();
            ByteBuf bb=Unpooled.copiedBuffer(resp,CharsetUtil.UTF_8);

            //构造一个响应
            FullHttpResponse response=new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK,bb);
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,bb.readableBytes());
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"application/json");
            channelHandlerContext.writeAndFlush(response);
        }
    }
}
